﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

using System.Diagnostics;
using System.Windows.Forms;

namespace SoundLeech
{
    class Convert2Mp3
    {
        delegate void SetTextCallback(TextBox tb);
        public static string WavToMP3(string sPathName_enc,
                         string sFileName_wav,
                         string sFileName_mp3, bool bWait)
        {
            try
            {
                ProcessStartInfo psi = new ProcessStartInfo();
                psi.UseShellExecute = false;
                psi.CreateNoWindow = true;      // No Command Prompt window.
                psi.WindowStyle = ProcessWindowStyle.Hidden;
                psi.FileName = "\"" + sPathName_enc + @"\lame.exe" + "\"";
                psi.Arguments = "-b 192 --resample 48 -m j " +
                                "\"" + sFileName_wav + "\"" + " " +
                                "\"" + sFileName_mp3 + "\"";
                Process p = Process.Start(psi);
                if (bWait)
                {
                    p.WaitForExit();
                }
                p.Close();
                p.Dispose();
                return "";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        static List<String> convertedFiles = new List<string>();
        static void SetText(TextBox tb)
        {
            tb.Lines = convertedFiles.ToArray();
        }
        public static void ConvertWav2Mp3(object data)
        {            
            TextBox tb = (((object[])data)[0] as TextBox) ;
            SetTextCallback d = new SetTextCallback(SetText);

            string inputFileName = (((object[])data)[1] as string)+".wav";
            Form parent = (((object[])data)[2] as Form);
            convertedFiles.Add("Converting " + inputFileName + " to MP3 ...");
            int idx = convertedFiles.Count() - 1;
            parent.Invoke(d, new object[] { tb });
            convertedFiles[idx] += "done.";
            WavToMP3("c:\\program files (x86)\\lame for audacity", inputFileName, Path.GetFileNameWithoutExtension(inputFileName) + ".mp3", true);
            File.Delete(inputFileName);
            parent.Invoke(d, new object[] { tb});
        }
    }
}
